import StringIO
from pgdump_rsync.dump_file import DumpFile
try:
    import librsync
except:
    import duplicity.librsync as librsync


class SyncServer:

    def __init__(self, filename):
        self.fd = open(filename, "rb")
        self.dump = DumpFile(self.fd)
        self.dump.calc_sizes()
        self.dump.calc_blobs_toc()

    def get_metadata(self):
        return self.dump.read_all_metadata()

    def get_entry_data(self, dump_id):
        entry = self.dump.find_entry(lambda te: te.dump_id == dump_id)
        if not entry:
            raise RuntimeError("Entry not found, dump_id = %s" % dump_id)
        return self.dump.read_data(entry)

    def get_size_and_hash(self, dump_id):
        entry = self.dump.find_entry(lambda te: te.dump_id == dump_id)
        if not entry:
            raise RuntimeError("Entry not found, dump_id = %s" % dump_id)
        if not entry.hash: # Not calculated yet
            self.dump.calc_hash(entry)
        return entry.size, entry.hash

    def get_blob_entries(self):
        return self.dump.blobs_toc

    def get_blob_data(self, oid):
        return self.dump.read_blob(oid)

    def calc_delta(self, dump_id, signature):
        entry = self.dump.find_entry(lambda te: te.dump_id == dump_id)
        if not entry:
            raise RuntimeError("Entry not found, dump_id = %s" % dump_id)
        f = StringIO.StringIO(self.dump.read_data(entry))
        delta_file = librsync.DeltaFile(signature, f)
        return delta_file.read()
